<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>更新头像</el-breadcrumb-item>
    </el-breadcrumb>

    <h4>更新头像</h4>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-upload class="avatar-uploader" :on-change="imgBroadcastChange" accept="image/jpg,image/png,image/jpeg" action="" :show-file-list="false" :auto-upload="false">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <el-button type="primary" @click="uploadAvatar">上传</el-button>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Avatar',
  data() {
    return {
      imageUrl: '',
    }
  },
  methods: {
    async uploadAvatar() {
      let params = new URLSearchParams()
      params.append('avatar', this.imageUrl)
      const { data: res } = await this.$http.post('/my/update/avatar', params)
      if (res.status !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
    },
    imgBroadcastChange(file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (isLt2M) {
        // uploadImgToBase64()返回一个Promise对象，通过.then()获取其数据。其中data.result是图片转成的base64值
        this.uploadImgToBase64(file.raw).then((data) => {
          this.imageUrl = data.result
        })
      } else {
        this.$message.error('上传封面图片大小不能超过 2MB!')
      }
    },
    uploadImgToBase64(file) {
      //核心方法，将图片转成base64字符串形式
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function () {
          // 图片转base64完成后返回reader对象
          resolve(reader)
        }
        reader.onerror = reject
      })
    },
  },
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
